# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from mycwpjt.items import Cra_technique_article


class TechniqueSpider(CrawlSpider):
    name = 'technique' #爬虫的名字
    allowed_domains = ['qnlm.ac'] #网页抓取允许的域名
    start_urls = ['http://www.qnlm.ac/page?a=14&b=1&c=397&p=detail'] #网页抓取的开始链接

    #网页抓取的规则
    rules = (
        Rule(LinkExtractor(allow=('b=1'), allow_domains = ('qnlm.ac')), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        #相当于new了一个item对象
        i = Cra_technique_article()
        #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
        #i['name'] = response.xpath('//div[@id="name"]').extract()
        #i['description'] = response.xpath('//div[@id="description"]').extract()
        #从网页中抓取的内容，保存到item项里
        i["title"] = response.xpath("//*[@id='datacontent']/div[1]/text()").extract_first()
        i["publish_time"] = response.xpath("//*[@id='datadate']/text()").extract_first()
        i["origin"] = response.xpath("//*[@id='ly']/text()").extract_first()
        i["url"] = response.request.url
        i["type"] = response.xpath("//*[@id='rightNavTitle']/text()").extract_first()
        i["author"] = response.xpath("//*[@id='txy']/text()").extract_first()
        i["content"] = response.xpath("//*[@id='datacontent']/div[3]//text()[normalize-space(.)]").extract()
        i["picture_loc"] = response.xpath("//*[@id='datacontent']/div[3]/p[3]/img/@src").extract_first()
        return i